<template>
  <div>
    <div class="header">
      <van-nav-bar
        title="搜索商品"
        left-arrow
        @click-left="$router.back()"
      />
      <van-search v-model="searchValue"
        placeholder="请输入搜索关键词" />
      <button @click="goSearch(searchValue)">搜索</button>
    </div>
    <div class="history" v-if="historyList.length > 0">
      <div class="upper">
        <span>最近搜索</span>
        <van-icon name="delete-o" @click="clear" />
      </div>
      <div class="body">
        <div class="resent" v-for="(item) in historyList" :key="item"
        @click="goSearch(item)">
          {{ item }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import { getHistoryList, setHistoryList } from '@/utils/storage'
import router from '@/router'

export default {
  name: 'SearchIndex',
  data () {
    return {
      searchValue: '',
      historyList: getHistoryList()
    }
  },
  methods: {
    goSearch (searchValue) {
      if (searchValue === '') return
      const index = this.historyList.indexOf(searchValue)
      if (index > -1) {
        this.historyList.splice(index, 1)
        this.historyList.unshift(searchValue)
      } else {
        this.historyList.unshift(searchValue)
      }
      setHistoryList(this.historyList)
      router.push(`/searchlist?search=${searchValue}`)
      this.searchValue = ''
    },
    clear () {
      this.historyList = []
      setHistoryList([])
      this.$toast.success('删除历史成功')
    }
  }
}
</script>
<style scoped lang="less">
.header {
  position: relative;
  .van-nav-bar {
    margin-bottom: 10px;
  }
  button {
    position: absolute;
    height: 34px;
    border: none;
    right: 12px;
    top: 66px;
    background-color: #e62121;
    width: 60px;
    border-radius: 0 5px 5px 0;
    color: rgba(255, 255, 255, 0.93);
  }
}
.history {
  margin-top: 20px;
  padding-left: 12px;
  padding-right: 12px;
  .upper {
    color: #151414;
    font-size: 18px;
    margin-bottom: 12px;
    .van-icon-delete-o {
      margin-left: 258px;
    }
  }
  .body {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    gap: 5%;
    .resent {
      width: 100px;
      height: 30px;
      text-align: center;
      line-height: 30px;
      font-size: 16px;
      border: 1px solid rgba(104, 104, 104, 0.25);
      border-radius: 30px;
      margin-bottom: 20px;
    }
  }
}

</style>
